<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.employeeName" placeholder="员工姓名" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <ASelect v-model="searchFrom.employeeStatus" placeholder="员工状态" allow-clear>
              <AOption label="在职" :value="0"></AOption>
              <AOption label="离职" :value="1"></AOption>
            </ASelect>
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <tableImp
            v-if="isAuth([1, 2])"
            imp-url="/system/employeeImport"
            :file-temp="() => onExport('template')"
            @end-call-back="onSearch"
          ></tableImp>
          <AButton status="danger" @click="batchDel()">批量删除</AButton>
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        v-model:selected-keys="selectedRowKeys"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :row-selection="{ showCheckedAll: true, type: 'checkbox' }"
        :span-method="spanMethod"
        span-all
        column-resizable
        size="small"
        row-key="employeeId"
      >
        <template #columns>
          <ATableColumn title="员工名称" data-index="employeeName" :width="100"></ATableColumn>
          <ATableColumn title="员工状态" data-index="employeeStatus" :width="100">
            <template #cell="{ record }">
              <div v-if="record.employeeStatus === 0">在职</div>
              <div v-else>离职</div>
            </template>
          </ATableColumn>
          <ATableColumn title="入职时间" data-index="entryDate" :width="100">
            <template #cell="{ record }">
              <div v-if="record.entryDate">{{ dayjs(record.entryDate).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="离职时间" data-index="quitDate" :width="100">
            <template #cell="{ record }">
              <div v-if="record.quitDate">{{ dayjs(record.quitDate).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn
            v-if="isAuth([1, 2])"
            title="操作"
            :width="150"
            fixed="right"
            align="center"
          >
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import { getTemplateUrl } from '@renderer/api/common'
import EditPopupForm from './editPopupForm.vue'
import { Message, Modal, TableInstance } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  batchDelEmployee,
  delEmployee,
  EmployeeListSearch,
  EmployeeResItem,
  getEmployeeAllList,
  getEmployeePageList
} from '@renderer/api/employee'
import tableImp from '@renderer/components/table/import.vue'
import { downloadFile } from '@renderer/utils/mixins'
import dayjs from 'dayjs'

const searchFrom = ref<EmployeeListSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<EmployeeResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const tableRef = ref<TableInstance>()
const selectedRowKeys = ref<string[]>([])

onMounted(() => {
  getTableData()
})

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectedRowKeys.value = []
}

function batchDel() {
  batchDelEmployee({ idList: selectedRowKeys.value }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

async function getTableData() {
  const res = await getEmployeePageList({ ...searchFrom.value, ...pageParam, orderBy: 0 })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 3) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
  clearTableSelect()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})

function rowEvent(row: EmployeeResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delEmployee({ employeeId: row.employeeId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break

    default:
      break
  }
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '员工名称', value: 'employeeName', width: 180 },
    { title: '员工状态', value: 'employeeStatus', width: 180 },
    { title: '入职时间', value: 'entryDate', width: 180 },
    { title: '离职时间', value: 'quitDate', width: 180 }
  ]
  let excelData: EmployeeResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '员工信息'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getEmployeeAllList(searchFrom.value)
        excelData = res.data.list.map((item, index) => {
          item.employeeStatus = item.employeeStatus == 0 ? '在职' : '离职'
          item.entryDate = item.entryDate ? dayjs(item.entryDate).format('YYYY-MM-DD') : ''
          item.quitDate = item.quitDate ? dayjs(item.quitDate).format('YYYY-MM-DD') : ''
          item.index = index + 1
          return item
        })
        import('@renderer/utils/vendor').then((excel) => {
          excel.exportExcel(excelData, headerData, fileTitle)
          exportLoad.value = false
        })
      }
      break
    case 'template':
      getTemplateUrl('/system/employeeTemplateUrl').then((res) => {
        downloadFile(res.data)
      })
      break
    default:
      break
  }
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
